#include "material.hpp"

Material::~Material()
{
}

PhongMaterial::PhongMaterial(const Colour& kd, const Colour& ks, double shininess,
 								double reflection, double refraction)
  : m_kd(kd), m_ks(ks), m_shininess(shininess), m_reflection(reflection), m_refraction(refraction)
{
}

PhongMaterial::~PhongMaterial()
{
}

void PhongMaterial::apply_gl() const
{
  // Perform OpenGL calls necessary to set up this material.
}

Colour PhongMaterial::get_diffuse() const
{
	return m_kd;
}

Colour PhongMaterial::get_specular() const
{
	return m_ks;
}

double PhongMaterial::get_shininess() const
{
	return m_shininess;
}
double PhongMaterial::get_reflection() const
{
	return m_reflection;
}
double PhongMaterial::get_refraction() const
{
	return m_refraction;
}
Texture::Texture(const std::string& filename)
{
	m_image = Image();
	if(!m_image.loadPng(filename)){
		std::cerr << "faile to load " << filename << " PNG file" << std::endl;
	}
}

Bump::Bump(const std::string& filename)
{
	m_image = Image();
	if(!m_image.loadPng(filename)){
		std::cerr << "faile to load " << filename << " PNG file" << std::endl;
	}
}


Vector3D Bump::extract_normal(double u, double v)
{
	
	u *= (m_image.width() -3 );
	v *= (m_image.height() - 3);
	int iu = (int) u;
	int iv = (int) v;
	float tu = u - iu;
	float tv = v - iv;
	double r = m_image(iu, iv, 0);
	double g = m_image(iu, iv, 1);
	double b = m_image(iu, iv, 2);
	Vector3D iuiv(r, g, b);
	r = m_image(iu+1, iv, 0);
	g = m_image(iu+1, iv, 1);
	b = m_image(iu+1, iv, 2);
	Vector3D iu1iv(r, g, b);

	r = m_image(iu, iv+1, 0);
	g = m_image(iu, iv+1, 1);
	b = m_image(iu, iv+1, 2);
	Vector3D iuiv1(r, g, b);

	r = m_image(iu+1, iv+1, 0);
	g = m_image(iu+1, iv+1, 1);
	b = m_image(iu+1, iv+1, 2);
	Vector3D iu1iv1(r, g, b);

	return (1-tu)*(1-tv)*iuiv + tu*(1-tv)*iu1iv + (1-tu)*tv*iuiv1 + tu*tv*iu1iv1;
/*
	int width = m_image.width();
	int height = m_image.height();
	int x = (int)(u*width);
	int y = (int)(v*height);
	x = x >= width? width-1:x;
	y = y >= height? height-1:y;
	double a = m_image(x,y,0);
	double b = m_image(x,y,1);
	double c = m_image(x,y,2);
	return Vector3D(a,b,c);
*/
}

Colour Texture::extract_colour(double u, double v)
{
	int width = m_image.width();
	int height = m_image.height();
	int x = (int)(u*width);
	int y = (int)(v*height);
	x = x >= width? width-1:x;
	y = y >= height? height-1:y;
	double a = m_image(x,y,0);
	double b = m_image(x,y,1);
	double c = m_image(x,y,2);
	return Colour(a,b,c);
}